import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:stacked/stacked.dart';
import 'package:qlevar_router/qlevar_router.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../comms_link/event_store.dart';
import '../../heartbeat/blueprint/event_model.dart';

/// 首页视图模型
class HomeNavigatorViewModel extends GatheringOrganizer {
  // 首页相关逻辑（复用 GatheringOrganizer 的数据与方法）
}

/// 首页
class HomeStory extends StatelessWidget {
  const HomeStory({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<HomeNavigatorViewModel>.reactive(
      viewModelBuilder: () => HomeNavigatorViewModel(),
      onModelReady: (vm) => vm.initializeDefaultGatherings(),
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 固定标题栏
                  _constructHeaderBar(),
                  // 可滚动内容
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          // 顶部图片
                          _renderTopBanner(),
                          _renderDecoration(),
                          // Challenge 标题
                          _displayChallengeSection(),
                          SizedBox(height: 16.h),
                          // 两张图片
                          _arrangeChallengeCards(),
                          SizedBox(height: 32.h),
                          // 活动列表
                          _composeEventSection(viewModel),
                          SizedBox(height: 130.h),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建固定标题栏
  Widget _constructHeaderBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          Text(
            'Marathon Assistant',
          ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
        ],
      ),
    );
  }

  /// 构建装饰图片
  Widget _renderDecoration() {
    return Padding(
      padding: EdgeInsets.only(top: 10.w, bottom: 0.w),
      child: Image.asset(MagmaConstant.decoration, fit: BoxFit.fitWidth),
    );
  }

  /// 构建顶部图片
  Widget _renderTopBanner() {
    return MagmaTap(
      onTap: () => QR.to(MagmaRouter.aiHelperPath),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(0.r),
          child: Image.asset(
            MagmaConstant.homeTop,
            fit: BoxFit.fitWidth,
            width: double.infinity,
          ),
        ),
      ),
    );
  }

  /// 构建Challenge标题
  Widget _displayChallengeSection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          'Challenge',
        ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
      ),
    );
  }

  /// 构建两张图片
  Widget _arrangeChallengeCards() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 第一张图片 - 宽高比 250/176
          Expanded(
            flex: 250,
            child: MagmaTap(
              onTap: () => QR.to(MagmaRouter.challengeListPath),
              child: AspectRatio(
                aspectRatio: 250 / 176,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(0.r),
                  child: Image.asset(
                    MagmaConstant.homeChallenge,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
          ),
          SizedBox(width: 8.w),
          // 第二张图片 - 宽高比 116/176
          Expanded(
            flex: 116,
            child: MagmaTap(
              onTap: () => QR.to(MagmaRouter.rankListPath),
              child: AspectRatio(
                aspectRatio: 116 / 176,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(0.r),
                  child: Image.asset(
                    MagmaConstant.homeRanking,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建活动列表
  Widget _composeEventSection(HomeNavigatorViewModel vm) {
    final List<GatheringModel> data = vm.gatherings;
    return Column(
      children: [
        // 活动标题
        Padding(
          padding: EdgeInsets.only(left: 16.w),
          child: Align(
            alignment: Alignment.centerLeft,
            child: Text(
              'Event Registration',
            ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
          ),
        ),
        SizedBox(height: 16.h),
        Container(
          padding: EdgeInsets.only(
            left: 12.w,
            right: 12.w,
            top: 0.w,
            bottom: 14.w,
          ),
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          decoration: BoxDecoration(
            border: Border.all(
              color: MagmaColor.white.withValues(alpha: 0.6),
              width: 1.w,
            ),
            borderRadius: BorderRadius.circular(2.r),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 活动描述
              Row(
                children: [
                  Expanded(
                    child: Text(
                      'Sprint towards the finish line, the brave ones are waiting for you at the starting line!',
                      style: TextStyle(height: 1.38),
                    ).inter(
                      fontSize: 16.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Image.asset(
                    MagmaConstant.homeEventDecoration,
                    fit: BoxFit.contain,
                    height: 100.h,
                  ),
                ],
              ),
              // 活动卡片列表（来自状态管理）
              ...data.asMap().entries.map(
                (e) => Padding(
                  padding: EdgeInsets.only(bottom: 12.h),
                  child: _generateEventCard(e.value, e.key),
                ),
              ),
              SizedBox(height: 0.h),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建活动卡片
  Widget _generateEventCard(GatheringModel gathering, int index) {
    return GestureDetector(
      onTap:
          () => QR.to(
            MagmaRouter.eventDetailPath.replaceAll(':eventId', gathering.id),
          ),
      child: AspectRatio(
        aspectRatio: 350 / 284,
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 14.w, horizontal: 12.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(2.r),
            image: DecorationImage(
              image: AssetImage(MagmaConstant.homeEventCard),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      gathering.title,
                      style: TextStyle(height: 1.62),
                    ).blackHanSans(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w400,
                      color: MagmaColor.black,
                    ),
                  ),
                  // 右上角重叠头像组
                  _stackedAvatars(index, _generateParticipantCount(index)),
                ],
              ),
              SizedBox(height: 12.h),
              // 活动图片
              Expanded(
                child: Stack(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(2.r)),
                      child: Image.asset(
                        gathering.image,
                        fit: BoxFit.cover,
                        width: double.infinity,
                        height: double.infinity,
                      ),
                    ),
                    // 报名按钮
                    Positioned(
                      bottom: 12.h,
                      right: 12.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: ShapeDecoration(
                          color: MagmaColor.purple,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(21.50.r),
                          ),
                          shadows: [
                            BoxShadow(
                              color: Color(0x338053CB),
                              blurRadius: 4,
                              offset: Offset(0, 4),
                              spreadRadius: 0,
                            ),
                          ],
                        ),
                        child: Center(
                          child: Text('Sign Up').blackHanSans(
                            fontSize: 16.sp,
                            color: MagmaColor.black,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  int _generateParticipantCount(int index) {
    final List<int> participantCounts = [3, 7, 12, 5, 9, 15, 8, 11];
    return participantCounts[index % participantCounts.length];
  }

  Widget _stackedAvatars(int index, int participantCount) {
    final List<String> avatars = [
      MagmaConstant.avatar1,
      MagmaConstant.avatar2,
      MagmaConstant.avatar3,
      MagmaConstant.avatar4,
      MagmaConstant.avatar5,
      MagmaConstant.avatar6,
    ];
    final int start = index % (avatars.length - 3);
    List<String> pick = avatars.sublist(start, start + 4);
    if (index.isOdd) {
      pick = pick.reversed.toList();
    }

    final double totalWidth = (pick.length * 14.w) + 26.6.w;

    return SizedBox(
      height: 26.6.w,
      width: totalWidth,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          for (int i = pick.length - 1; i >= 0; i--)
            Positioned(
              right: 14.w + (i * 14.w),
              child: _createUserAvatar(pick[i]),
            ),
          Positioned(
            right: 0,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(26.6.w),
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                child: Container(
                  width: 26.6.w,
                  height: 26.6.w,
                  decoration: BoxDecoration(
                    color: MagmaColor.purple.withOpacity(0.2),
                    shape: BoxShape.circle,
                    border: Border.all(color: MagmaColor.black, width: 1.w),
                  ),
                  child: Center(
                    child: Text('+$participantCount').blackHanSans(
                      fontSize: 12.sp,
                      color: MagmaColor.black,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户头像
  Widget _createUserAvatar(String avatarPath) {
    return Container(
      width: 26.6.w,
      height: 26.6.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: MagmaColor.black, width: 1.w),
      ),
      child: ClipOval(child: Image.asset(avatarPath, fit: BoxFit.cover)),
    );
  }
}
